

let mapKey: string | null = null;
let mapKeyIndex = 0;
let keyArr: string[] = [];

const aGetMapKey = () => mapKey


const requestReject = (reject: (p: { status: number }) => void) =>
	reject({ status: 500 });

type RequestParams = {
	url: string;
	data: Record<string, any>;
};
type RequestData<T> = {
	status: string;
	regeocode: T;
	geocodes: T
	info:string
};
// 高德地图info字段枚举详见https://lbs.amap.com/api/webservice/guide/tools/info
const Request = <T = any>({ url, data }: RequestParams) =>
	new Promise<RequestData<T>>((resolve, reject) => {
		uni.request({
			url:`https://restapi.amap.com/v3/${url}`,
			data,
			success: (res) => {
				if (res.statusCode == 200) {
					const requestData = res.data as RequestData<T>
					if (requestData.status === '1') {
						resolve(requestData);
					} else {
						if (['INVALID_USER_KEY','SERVICE_NOT_AVAILABLE','USER_DAILY_QUERY_OVER_LIMIT'].includes(requestData.info)) {
							reRequest<T>(
								{
									url,
									data,
								},
								true
							)
								.then((res) => {
									resolve(res);
								})
								.catch(() => requestReject(reject));
						} else {
							console.error("请求错误", res);
							requestReject(reject);
						}
					}
				} else {
					console.error("请求失败");
					requestReject(reject);
				}
			},
			fail: (err) => {
				console.log(err, url);
				requestReject(reject);
			},
		});


	});

const reRequest = <T>(
	params: {
		url: string;
		data: Record<string, any>;
	},
	switchKey: boolean
) =>
	new Promise<RequestData<T>>((resolve, reject) => {
		if (switchKey) {
			if (!keyArr.length || mapKeyIndex === keyArr.length - 1) {
				reject("error");
			} else {
				mapKeyIndex++;
				mapKey = keyArr[mapKeyIndex];
			}
		}
		Request<T>(params)
			.then((res) => resolve(res))
			.catch((err) => reject(err));
	});

const aLoadMapScript = (arr: string[]) => {
	
};

// 逆地址解析
const aGeolocation = (latitude: number, longitude: number, isGeolocation = true): Promise<{
	address_component: {
		district:string
		city:string
		province:string
	}
	latitude:number
	longitude:number
	address:string
}> =>
	new Promise((resolve, reject) => {
		let data = {
			key: mapKey,
			location: latitude + ',' + longitude
		}
		if (isGeolocation) {
			Request({
				url: 'geocode/regeo',
				data: {
					...data,
				}
			})
				.then(res => {
					let {
						district,
						city,
						province
					} = res.regeocode.addressComponent
	
					let data = {
						address_component: {
							district,
							city,
							province
						},
						latitude,
						longitude,
						address:''
					}
					uni.setStorageSync('userGeolocation', data)
					resolve(data)
				})
				.catch(err => reject(err))
		} else {
			let _data = {
				address_component: {
					district: '',
					city: '',
					province: '',
				},
				latitude,
				longitude,
				address:''
			}
			uni.setStorageSync('userGeolocation', _data)
			resolve(_data)
		}

	})

// 根据地址信息转换经纬度
const aAddressToLocation = (address: string): Promise<{
	longitude: number,
	latitude: number,
}> => {
	return new Promise((resolve, reject) => {
		let data = {
			key: mapKey,
			address,
		};
		Request<{
			location: string;
		}>({
			url: "geocode/geo",
			data,
		})
			.then((res) => {
				const [longitude,latitude] = res.geocodes.location.split(',')
				resolve({
					longitude:Number(longitude),
					latitude:Number(latitude),
				});
			})
			.catch((err) => reject(err));
	});
};


export {
	aGetMapKey,
	aLoadMapScript,
	aGeolocation,
	aAddressToLocation,
}
